package cn.lingyangwl.agile.gateway.body;

import cn.lingyangwl.agile.model.module.auth.LoginUser;
import com.alibaba.fastjson2.annotation.JSONField;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;

import java.util.HashMap;
import java.util.Map;

/**
 * 请求上下文
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class GatewayContext {

    public static final String CACHE_GATEWAY_CONTEXT = "cacheGatewayContext";

    private Long startTime;
    /**
     * cache json body
     */
    private String cacheBody = "";
    /**
     * cache formdata,表单数据
     */
    private MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
    /**
     * url数据，拼接在路径上的参数
     */
    private MultiValueMap<String, String> urlData = new LinkedMultiValueMap<>();
    /**
     * cache reqeust path
     */
    private String path;

    @JSONField(serialize = false)
    private ServerWebExchange exchange;

    /**
     * 添加新的请求头
     */
    private Map<String, String> addRequestHeaders = new HashMap<>();

    /**
     * 登录用户信息
     */
    private LoginUser loginUser;

    private String tenantId;
    private String mainTenantId;

    public static GatewayContext getContext(ServerWebExchange exchange) {
        GatewayContext gatewayContext = exchange.getAttribute(GatewayContext.CACHE_GATEWAY_CONTEXT);
        if (gatewayContext == null) {
            gatewayContext = new GatewayContext();
        }
        gatewayContext.exchange = exchange;
        return gatewayContext;
    }

    public void addRequestHeader(String key, String value) {
        addRequestHeaders.put(key, value);
    }
}
